package com.example.javaairportflightanalysis.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.example.javaairportflightanalysis.comparator.StatusComparator;
import com.example.javaairportflightanalysis.dao.CheckMapper;
import com.example.javaairportflightanalysis.dao.DfdlCheckMapper;
import com.example.javaairportflightanalysis.dao.DfdlMapper;
import com.example.javaairportflightanalysis.dao.UserMapper;
import com.example.javaairportflightanalysis.domin.check.Check;
import com.example.javaairportflightanalysis.domin.check.DfdlCheckAD;
import com.example.javaairportflightanalysis.domin.check.TransferCheckAD;
import com.example.javaairportflightanalysis.domin.merge.DfdlStatusDto;
import com.example.javaairportflightanalysis.domin.merge.TransferStatusDto;
import com.example.javaairportflightanalysis.exception.MyException;
import com.example.javaairportflightanalysis.exception.MyExceptionEnum;
import com.example.javaairportflightanalysis.service.DfdlCheckService;
import com.example.javaairportflightanalysis.utils.GroupAndPageUtil;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

/**
 * @author shen
 */
@Service
@Slf4j
public class DfdlCheckServiceImpl implements DfdlCheckService {
    /**
     * 如果更改数据，则把数据放到表中
     */
    @Resource
    DfdlCheckMapper dfdlCheckMapper;
    @Resource
    DfdlMapper dfdlMapper;
    @Resource
    UserMapper  userMapper;
    @Resource
    CheckMapper checkMapper;

    /**
     *到港直达航班
     */
    @Override
    public Integer updateDfdlCheckA(Integer id, DfdlCheckAD dfdlCheckAD) {
        DfdlStatusDto dfdlStatusDtoExisting = dfdlMapper.selectAById(id);
        // uuid为空，表示是第一次审核
        if (Objects.isNull(dfdlStatusDtoExisting.getUuid())) {
            insertCheckA2(id, dfdlCheckAD);
            Integer result = dfdlCheckMapper.insertDfdlCheckA(dfdlCheckAD);
            if (result != 1) {
                throw new MyException(MyExceptionEnum.INSERT_ERROR);
            }
            return result;
        } else {
            DfdlCheckAD newDfdlCheckAD = dfdlCheckMapper.selectByUuidA(dfdlStatusDtoExisting.getUuid());
            if (newDfdlCheckAD!=null&&newDfdlCheckAD.getStatus() != 1&& !Objects.equals(newDfdlCheckAD.getUuid(), dfdlCheckAD.getUuid())) {
                // 处于审核状态
                throw new MyException(MyExceptionEnum.CHECK_STATUS_ERROR);
            } else {
                insertCheckA2(id, dfdlCheckAD);
                return dfdlCheckMapper.insertDfdlCheckA(dfdlCheckAD);
            }
        }
    }
    @Override
    public PageInfo selectAllDfdlCheckA(Integer pageNum, Integer pageSize){
        List<DfdlCheckAD> dfdlCheckADS = dfdlCheckMapper.selectAllDateA(pageNum, pageSize);
        //按照状态排序
        StatusComparator<DfdlCheckAD> comparator = new StatusComparator<>(DfdlCheckAD::getStatus);
        dfdlCheckADS.sort(comparator);
        PageInfo<DfdlCheckAD> newDfdlCheckAD = new PageInfo<>(dfdlCheckADS);
        return newDfdlCheckAD;
    }
    /**
     * 插入A2审核表
     * 到港直达航班
     */
    private void insertCheckA2(Integer id, DfdlCheckAD dfdlCheckAD) {
        String uuid = GroupAndPageUtil.getUUID();
        dfdlCheckMapper.updateStatusA(1, uuid,id);
        dfdlCheckAD.setUuid(uuid);
        dfdlCheckAD.setStatus(1);
        boolean login = StpUtil.isLogin();
        log.info("=======login:{}=======",login);
        Object loginIdObj = StpUtil.getLoginId();
        if (loginIdObj instanceof String) {
            Integer loginId = Integer.parseInt((String) loginIdObj);
            Check check = setModifierCheck(loginId, uuid,"到港直达航班");
            log.info("=======check:{}=======",check);
            checkMapper.insertCheck(check);
        }else {
            throw new MyException(MyExceptionEnum.LOGIN_ERROR);
        }
    }

    /**
     * 到港中转航班
     */
    @Override
    public PageInfo selectAllTransferCheckA(Integer pageNum, Integer pageSize){
        List<TransferCheckAD> transferCheckADS = dfdlCheckMapper.selectAllTransferA(pageNum, pageSize);
        //按照状态排序
        StatusComparator<TransferCheckAD> comparator = new StatusComparator<>(TransferCheckAD::getStatus);
        transferCheckADS.sort(comparator);
        PageInfo<TransferCheckAD> newTransferCheckAD = new PageInfo<>(transferCheckADS);
        return newTransferCheckAD;
    }
    @Override
    public Integer updateTransferCheckA(Integer id, TransferCheckAD transferCheckAD) {
        TransferStatusDto transferStatusDto = dfdlMapper.selectTransferAById(id);
        // uuid为空，表示是第一次审核
        if (Objects.isNull(transferStatusDto.getUuid())) {
            insertCheckA3(id, transferCheckAD);
            Integer result = dfdlCheckMapper.insertTransferCheckA(transferCheckAD);
            if (result != 1) {
                throw new MyException(MyExceptionEnum.INSERT_ERROR);
            }
            return result;
        } else {
            TransferCheckAD transferUuidA = dfdlCheckMapper.selectByTransferUuidA(transferStatusDto.getUuid());
            if (transferUuidA!=null&&transferUuidA.getStatus() != 1&& !Objects.equals(transferUuidA.getUuid(), transferCheckAD.getUuid())) {
                // 处于审核状态
                throw new MyException(MyExceptionEnum.CHECK_STATUS_ERROR);
            } else {
                insertCheckA3(id, transferCheckAD);
                return dfdlCheckMapper.insertTransferCheckA(transferCheckAD);
            }
        }
    }
    /**
     * 插入A的中转待审核表
     * 到港中转航班
     * @param id
     */
    private void insertCheckA3(Integer id, TransferCheckAD transferCheckAD) {
        String uuid = GroupAndPageUtil.getUUID();
        //更新原始表的状态：将状态1待审核和uuid根据id更新到Transfer_A表中
        dfdlCheckMapper.updateTransferStatusA(1, uuid,id);
        transferCheckAD.setUuid(uuid);
        transferCheckAD.setStatus(1);
        boolean login = StpUtil.isLogin();
        log.info("=======login:{}=======",login);
        Object loginIdObj = StpUtil.getLoginId();
        if (loginIdObj instanceof String) {
            Integer loginId = Integer.parseInt((String) loginIdObj);
            //插入check表的修改人和创建时间
            Check check = setModifierCheck(loginId, uuid,"到港中转航班");
            checkMapper.insertCheck(check);
        }else {
            throw new MyException(MyExceptionEnum.LOGIN_ERROR);
        }
    }

    /**
     * 离港直达航班
     */
    @Override
    public PageInfo selectAllDfdlCheckD(Integer pageNum, Integer pageSize) {
        List<DfdlCheckAD> dfdlCheckADS = dfdlCheckMapper.selectAllDateD(pageNum, pageSize);
        //按照状态排序
        StatusComparator<DfdlCheckAD> comparator = new StatusComparator<>(DfdlCheckAD::getStatus);
        dfdlCheckADS.sort(comparator);
        PageInfo<DfdlCheckAD> newDfdlCheckAD = new PageInfo<>(dfdlCheckADS);
        return newDfdlCheckAD;
    }
    @Override
    public Integer updateDfdlCheckD(Integer id, DfdlCheckAD dfdlCheckAD) {
        //D：根据传过来的对象
        DfdlStatusDto dfdlStatusDtoExisting = dfdlMapper.selectDById(id);
        // uuid为空，表示是第一次审核
        if (Objects.isNull(dfdlStatusDtoExisting.getUuid())) {
            insertCheckD2(id, dfdlCheckAD);
            //把数据插到Dfdl_Check_D
            Integer result = dfdlCheckMapper.insertDfdlCheckD(dfdlCheckAD);
            if (result != 1) {
                throw new MyException(MyExceptionEnum.INSERT_ERROR);
            }
            return result;
        } else {
            DfdlCheckAD newDfdlCheckAD = dfdlCheckMapper.selectByUuidD(dfdlStatusDtoExisting.getUuid());
            if (newDfdlCheckAD!=null&&newDfdlCheckAD.getStatus() != 1) {
                // 处于审核状态
                throw new MyException(MyExceptionEnum.CHECK_STATUS_ERROR);
            } else {
                insertCheckD2(id, dfdlCheckAD);
                return dfdlCheckMapper.insertDfdlCheckD(dfdlCheckAD);
            }
        }
    }
    private void insertCheckD2(Integer id, DfdlCheckAD dfdlCheckAD) {
        String uuid = GroupAndPageUtil.getUUID();
        dfdlCheckMapper.updateDStatus(1, uuid,id);
        dfdlCheckAD.setUuid(uuid);
        dfdlCheckAD.setStatus(1);
        Object loginIdObj = StpUtil.getLoginId();
        if (loginIdObj instanceof String) {
            Integer loginId = Integer.parseInt((String) loginIdObj);

            Check check = setModifierCheck(loginId, uuid,"离港直达航班");
            log.info("=======check:{}=======",check);
            checkMapper.insertCheck(check);
        }else {
            throw new MyException(MyExceptionEnum.LOGIN_ERROR);
        }
    }

    /**
     * 离港中转航班
     */
    @Override
    public PageInfo selectAllTransferCheckD(Integer pageNum, Integer pageSize){
        List<TransferCheckAD> transferCheckADS = dfdlCheckMapper.selectAllTransferD(pageNum, pageSize);
        //按照状态排序
        StatusComparator<TransferCheckAD> comparator = new StatusComparator<>(TransferCheckAD::getStatus);
        transferCheckADS.sort(comparator);
        PageInfo<TransferCheckAD> newTransferCheckAD = new PageInfo<>(transferCheckADS);
        return newTransferCheckAD;
    }
    @Override
    public Integer updateTransferCheckD(Integer id, TransferCheckAD transferCheckAD) {
        TransferStatusDto transferStatusDto = dfdlMapper.selectTransferDById(id);
        // uuid为空，表示是第一次审核
        if (Objects.isNull(transferStatusDto.getUuid())) {
            insertCheckD3(id, transferCheckAD);
            Integer result = dfdlCheckMapper.insertTransferCheckD(transferCheckAD);
            if (result != 1) {
                throw new MyException(MyExceptionEnum.INSERT_ERROR);
            }
            return result;
        } else {
            TransferCheckAD transferUuidA = dfdlCheckMapper.selectByTransferUuidD(transferStatusDto.getUuid());
            if (transferUuidA!=null&&transferUuidA.getStatus() != 1&& !Objects.equals(transferUuidA.getUuid(), transferCheckAD.getUuid())) {
                // 处于审核状态
                throw new MyException(MyExceptionEnum.CHECK_STATUS_ERROR);
            } else {
                insertCheckD3(id, transferCheckAD);
                return dfdlCheckMapper.insertTransferCheckD(transferCheckAD);
            }
        }
    }
    /**
     * 插入A的中转待审核表
     * 到港中转航班
     * @param id
     */
    private void insertCheckD3(Integer id, TransferCheckAD transferCheckAD) {
        String uuid = GroupAndPageUtil.getUUID();
        //更新原始表的状态：将状态1待审核和uuid根据id更新到Transfer_A表中
        dfdlCheckMapper.updateTransferStatusD(1, uuid,id);
        transferCheckAD.setUuid(uuid);
        transferCheckAD.setStatus(1);
        boolean login = StpUtil.isLogin();
        log.info("=======login:{}=======",login);
        Object loginIdObj = StpUtil.getLoginId();
        if (loginIdObj instanceof String) {
            Integer loginId = Integer.parseInt((String) loginIdObj);
            //插入check表的修改人和创建时间
            Check check = setModifierCheck(loginId, uuid,"离港中转航班");
            checkMapper.insertCheck(check);
        }else {
            throw new MyException(MyExceptionEnum.LOGIN_ERROR);
        }
    }

    /**
     * 设置修改的各种参数
     * @param id 根据id查出修改人
     * @param uuid 一样的uuid，方便进行连接
     * @param flightType 航班类型
     * @return
     */
    private Check setModifierCheck(Integer id,String uuid,String flightType) {
        // modifier
        String modifierUsername =  userMapper.selectById(id).getUsername();

        Check check = new Check();
        //设置修改人
        check.setModifier(modifierUsername);
        //获取当前修改的时间
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedTime = currentTime.format(formatter);
        check.setCreateTime(formattedTime);
        //1 为正在审核
        check.setStatus(1);
        //设置相同的UUID
        check.setUuid(uuid);
        check.setFlightType(flightType);
        return check;
    }

}
